package com.huluobo.a2206monthdemo.live;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.ImageView;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.huluobo.a2206monthdemo.R;
import com.huluobo.a2206monthdemo.adapter.GiftAdapter;
import com.huluobo.a2206monthdemo.adapter.MessageAdapter;
import com.huluobo.a2206monthdemo.databinding.ActivityLiveBinding;
import com.huluobo.a2206monthdemo.pay.PayActivity;
import com.huluobo.a2206monthdemo.utils.ImageUtils;
import com.huluobo.base.bean.CommonBeanResult;
import com.huluobo.base.bean.GiftBeanResult;
import com.huluobo.base.bean.Money;
import com.huluobo.base.bean.VideoBeanResult;
import com.huluobo.base.db.AppDBUtils;
import com.huluobo.base.mvvm.BaseMVVMActivity;
import com.huluobo.base.net.Const;
import com.hyphenate.EMCallBack;
import com.hyphenate.EMChatRoomChangeListener;
import com.hyphenate.EMMessageListener;
import com.hyphenate.EMValueCallBack;
import com.hyphenate.chat.EMChatRoom;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMTextMessageBody;

import java.util.List;

import master.flame.danmaku.danmaku.model.BaseDanmaku;
import master.flame.danmaku.danmaku.model.IDanmakus;
import master.flame.danmaku.danmaku.model.android.DanmakuContext;
import master.flame.danmaku.danmaku.model.android.Danmakus;
import master.flame.danmaku.danmaku.parser.BaseDanmakuParser;

public class LiveActivity extends BaseMVVMActivity<ActivityLiveBinding, LiveViewModel> {

    private VideoBeanResult.VideoBean videoBean;
    private GiftAdapter giftAdapter;
    private GiftBeanResult.GIftBean gIftBean;
    private Money money;
    private MessageAdapter messageAdapter;

    @Override
    protected void initData() {
        viewModel.followAuthSuccess.observe(this, commonBeanResult -> {
            ToastUtils.showLong(commonBeanResult.getMessage());
            if (commonBeanResult.getCode() == 200) {
                videoBean.setGuanzhu(1);
                binding.liveFollowBtn.setText("已关注");
                binding.liveFollowBtn.setBackgroundResource(R.drawable.shape_black);
            }
        });

        viewModel.followAuthFailed.observe(this, s -> {
            Log.i("TagA", "关注失败:" + s);
        });

        viewModel.cancelFollowSuccess.observe(this, commonBeanResult -> {
            ToastUtils.showLong(commonBeanResult.getMessage());
            if (commonBeanResult.getCode() == 200) {
                videoBean.setGuanzhu(0);
                binding.liveFollowBtn.setText("关注");
                binding.liveFollowBtn.setBackgroundResource(R.drawable.shape_red);
            }
        });

        viewModel.cancelFollowFailed.observe(this, s -> {
            Log.i("TagA", "取消关注失败:" + s);
        });

        viewModel.getGiftSuccess.observe(this, giftBeanResult -> {
            if (giftBeanResult.getCode() == 200) {
                giftAdapter.getData().clear();
                giftAdapter.getData().addAll(giftBeanResult.getData());
                giftAdapter.notifyDataSetChanged();
            } else {
                ToastUtils.showLong(giftBeanResult.getMessage());
            }
        });

        viewModel.getGiftFailed.observe(this, s -> {
            Log.i("TagA", "获取礼物失败:" + s);
        });
    }

    @Override
    protected void initView() {
        videoBean = (VideoBeanResult.VideoBean) getIntent().getSerializableExtra("videoBean");

        binding.liveGsyPlayer.getBackButton().setVisibility(View.GONE);
        binding.liveGsyPlayer.setUp(videoBean.getVideopath(), true, "");
//        binding.liveGsyPlayer.startPlayLogic();

        ImageUtils.getInstance().loadCircleImage(this, videoBean.getHeadpath(), binding.liveUserIconIv);
        binding.liveUsernameTv.setText(videoBean.getAuthname());
        binding.liveFollowBtn.setText(videoBean.getGuanzhu() == 0 ? "关注" : "已关注");
        binding.liveFollowBtn.setBackgroundResource(videoBean.getGuanzhu() == 0 ? R.drawable.shape_red :
                R.drawable.shape_black);
        binding.liveLikeCountTv.setText(videoBean.getLike_count() + "人喜欢");
        binding.liveFollowBtn.setOnClickListener(v -> {
            if (videoBean.getGuanzhu() == 0) {
                //未关注
                viewModel.followAuth(videoBean.getAuthname());
            } else {
                //已关注
                viewModel.cancelFollow(videoBean.getAuthname());
            }
        });

        binding.liveLikeView.addLikeImages(
                R.drawable.fav_0,
                R.drawable.fav_1,
                R.drawable.fav_2,
                R.drawable.fav_3,
                R.drawable.fav_4,
                R.drawable.fav_5
        );

        binding.liveLikeIv.setOnClickListener(v -> {
            binding.liveLikeView.addFavor();
        });

        binding.liveDanmuIv.setOnClickListener(v -> {
            binding.liveDanmuInputLayoutLl.setVisibility(View.VISIBLE);
        });

        initDanmuView();

        binding.liveDanmuSendIv.setOnClickListener(v -> {
            sendDanmu();
        });

        binding.liveGiftIv.setOnClickListener(v -> {
            binding.liveGiftLayoutCl.setVisibility(View.VISIBLE);
            viewModel.getGiftList();
        });

        binding.liveGiftRv.setLayoutManager(new GridLayoutManager(this, 5));
        giftAdapter = new GiftAdapter();
        binding.liveGiftRv.setAdapter(giftAdapter);

        giftAdapter.setOnItemClickListener((adapter, view, position) -> {
            gIftBean = giftAdapter.getData().get(position);
            ImageUtils.getInstance().loadImage(this, gIftBean.getGiftpath(), binding.liveGiftSelectIv);
            binding.liveGiftSelectTv.setText(gIftBean.getGiftname());
        });

        binding.liveCloseTv.setOnClickListener(v -> {
            binding.liveGiftLayoutCl.setVisibility(View.GONE);
        });

        binding.liveGiftSendBtn.setOnClickListener(v -> {
            sendGift();
        });

        money = AppDBUtils.getInstance().getMoneyDao().queryUserMoneyByName(SPUtils.getInstance().getString(Const.PARAM_USERNAME));

        binding.liveUserMoneyTv.setText(
                "用户余额:" + money.getMoney() + "抖币"
        );

        binding.livePayBtn.setOnClickListener(v -> {
            Intent intent = new Intent(this, PayActivity.class);
            startActivity(intent);
        });

        binding.liveInputTv.setOnClickListener(v -> {
            binding.liveChatLayoutLl.setVisibility(View.VISIBLE);
        });

        binding.liveChatRv.setLayoutManager(new LinearLayoutManager(this));
        messageAdapter = new MessageAdapter();
        binding.liveChatRv.setAdapter(messageAdapter);

        binding.liveChatSendIv.setOnClickListener(v -> {
//            String msg = binding.liveChatInputEt.getText().toString();
//            if (msg.isEmpty()) {
//                ToastUtils.showLong("请输入聊天内容");
//                return;
//            }
//            String username = SPUtils.getInstance().getString(Const.PARAM_USERNAME);
//            MessageEntity message = new MessageEntity(username, msg);
//            messageAdapter.getData().add(message);
//            messageAdapter.notifyDataSetChanged();
//            binding.liveChatRv.scrollToPosition(messageAdapter.getData().size() - 1);
//            binding.liveChatInputEt.setText("");
//            binding.liveChatLayoutLl.setVisibility(View.GONE);
            sendMessage(Const.ROOM_ID, binding.liveChatInputEt.getText().toString());
        });

        initChatRoom();
    }

    private void sendMessage(String roomId, String content) {
        EMMessage emMessage = EMMessage.createTextSendMessage(content, roomId);
        emMessage.setChatType(EMMessage.ChatType.ChatRoom);
        emMessage.setBody(new EMTextMessageBody(content));
        EMClient.getInstance().chatManager().sendMessage(emMessage);
        emMessage.setMessageStatusCallback(new EMCallBack() {
            @Override
            public void onSuccess() {
                runOnUiThread(() -> {
                    MessageEntity message = new MessageEntity(SPUtils.getInstance().getString(Const.PARAM_USERNAME),
                            content);
                    messageAdapter.getData().add(message);
                    messageAdapter.notifyDataSetChanged();
                    binding.liveChatRv.scrollToPosition(messageAdapter.getData().size() - 1);
                    binding.liveChatInputEt.setText("");
                    binding.liveChatLayoutLl.setVisibility(View.GONE);
                });
            }

            @Override
            public void onError(int code, String error) {
                Log.i("TagA", "发送消息失败:" + error + ",code:" + code);
            }
        });
    }

    private void initChatRoom() {
        EMClient.getInstance().chatManager().addMessageListener(messageListener);
        EMClient.getInstance().chatroomManager().addChatRoomChangeListener(emChatRoomChangeListener);
        EMClient.getInstance().chatroomManager().joinChatRoom(Const.ROOM_ID, new EMValueCallBack<EMChatRoom>() {
            @Override
            public void onSuccess(EMChatRoom value) {
                Log.i("TagA", "加入聊天室成功");
            }

            @Override
            public void onError(int error, String errorMsg) {
                Log.i("TagA", "加入聊天室失败:" + error + "msg:" + errorMsg);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EMClient.getInstance().chatroomManager().leaveChatRoom(Const.ROOM_ID);
        EMClient.getInstance().chatManager().removeMessageListener(messageListener);
        EMClient.getInstance().chatroomManager().removeChatRoomListener(emChatRoomChangeListener);
    }

    private EMMessageListener messageListener = new EMMessageListener() {
        @Override
        public void onMessageReceived(List<EMMessage> messages) {
            Log.i("TagA", "接收到新消息:" + messages.get(0).toString());
        }
    };

    private EMChatRoomChangeListener emChatRoomChangeListener = new EMChatRoomChangeListener() {
        @Override
        public void onChatRoomDestroyed(String roomId, String roomName) {

        }

        @Override
        public void onMemberJoined(String roomId, String participant) {
            Log.i("TagA", "有成员进入:" + participant);
        }

        @Override
        public void onMemberExited(String roomId, String roomName, String participant) {
            Log.i("TagA", "有成员退出:" + participant);
        }

        @Override
        public void onRemovedFromChatRoom(int reason, String roomId, String roomName, String participant) {

        }

        @Override
        public void onMuteListAdded(String chatRoomId, List<String> mutes, long expireTime) {

        }

        @Override
        public void onMuteListRemoved(String chatRoomId, List<String> mutes) {

        }

        @Override
        public void onWhiteListAdded(String chatRoomId, List<String> whitelist) {

        }

        @Override
        public void onWhiteListRemoved(String chatRoomId, List<String> whitelist) {

        }

        @Override
        public void onAllMemberMuteStateChanged(String chatRoomId, boolean isMuted) {

        }

        @Override
        public void onAdminAdded(String chatRoomId, String admin) {

        }

        @Override
        public void onAdminRemoved(String chatRoomId, String admin) {

        }

        @Override
        public void onOwnerChanged(String chatRoomId, String newOwner, String oldOwner) {

        }

        @Override
        public void onAnnouncementChanged(String chatRoomId, String announcement) {

        }
    };

    private void sendGift() {
        if (gIftBean == null || money == null) {
            ToastUtils.showLong("请选择礼物,或者查询余额失败");
            return;
        }

        if (money.getMoney() < gIftBean.getPrice()) {
            ToastUtils.showLong("余额不足,请充值");
            return;
        }

        float newMoney = money.getMoney() - gIftBean.getPrice();
        binding.liveUserMoneyTv.setText("余额:" + newMoney + "抖币");

        money.setMoney(newMoney);
        AppDBUtils.getInstance().getMoneyDao().updateUserMoney(money);

        ImageView giftView = new ImageView(this);
        ConstraintLayout.LayoutParams params = new ConstraintLayout.LayoutParams(200, 200);
        giftView.setLayoutParams(params);

        binding.liveRootCl.addView(giftView);
        ImageUtils.getInstance().loadImage(this, gIftBean.getGiftpath(), giftView);

        float screenWidth = binding.liveRootCl.getMeasuredWidth();
        float screenHeight = binding.liveRootCl.getMeasuredHeight();

        ObjectAnimator translationY = ObjectAnimator.ofFloat(giftView, "translationY", screenHeight, screenHeight / 2
                , screenHeight / 5, screenHeight / 3, screenHeight / 2);
        ObjectAnimator translationX = ObjectAnimator.ofFloat(giftView, "translationX", screenWidth / 2,
                screenWidth / 5, screenWidth / 2, screenWidth / 3 * 2, screenWidth / 2);

        ObjectAnimator rotation = ObjectAnimator.ofFloat(giftView, "rotation", 0, 1800);
        ObjectAnimator scaleX = ObjectAnimator.ofFloat(giftView, "scaleX", 1, 2, 1, 3, 1, 2, 1);
        ObjectAnimator scaleY = ObjectAnimator.ofFloat(giftView, "scaleY", 1, 2, 1, 3, 1, 2, 1);

        AnimatorSet set = new AnimatorSet();
        set.setDuration(3000);
        set.setInterpolator(new AccelerateDecelerateInterpolator());
        set.playTogether(translationX, translationY, rotation, scaleX, scaleY);
        set.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
                binding.liveGiftLayoutCl.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                binding.liveRootCl.removeView(giftView);
            }
        });
        set.start();
    }

    private void sendDanmu() {
        String danmuString = binding.liveDanmuInputEt.getText().toString();
        if (danmuString.isEmpty()) {
            ToastUtils.showLong("请输入弹幕内容,不能为空");
            return;
        }

        binding.liveDanmuView.clear();
        binding.liveDanmuView.removeAllDanmakus(true);

        BaseDanmaku danmaku = danmakuContext.mDanmakuFactory.createDanmaku(BaseDanmaku.TYPE_SCROLL_RL);
        danmaku.text = danmuString;
        danmaku.textSize = 30;
        danmaku.textColor = Color.WHITE;
        danmaku.padding = 10;
        danmaku.setTime(800);

        binding.liveDanmuView.addDanmaku(danmaku);
        binding.liveDanmuView.start();

        binding.liveDanmuInputEt.postDelayed(() -> {
            binding.liveDanmuInputEt.setText("");
            binding.liveDanmuInputLayoutLl.setVisibility(View.GONE);
        }, 300);
    }

    private DanmakuContext danmakuContext;

    private void initDanmuView() {
        binding.liveDanmuView.enableDanmakuDrawingCache(false);
        binding.liveDanmuView.clear();
        binding.liveDanmuView.removeAllDanmakus(true);

        danmakuContext = DanmakuContext.create();
        binding.liveDanmuView.prepare(new BaseDanmakuParser() {
            @Override
            protected IDanmakus parse() {
                return new Danmakus();
            }
        }, danmakuContext);

    }

    @Override
    protected Class<LiveViewModel> getViewModel() {
        return LiveViewModel.class;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_live;
    }

    @Override
    protected void onResume() {
        super.onResume();
        money = AppDBUtils.getInstance().getMoneyDao().queryUserMoneyByName(SPUtils.getInstance().getString(Const.PARAM_USERNAME));
    }
}